package com.tsk.custom.rule;

import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.project.MavenProject;
import org.apache.maven.rtinfo.RuntimeInformation;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author: 黄嘉振
 * @create: 2023/4/21 10:55
 * @description:    校验子项目中是否显示配置version
 **/
@Named("requireCheckVersion")
public class RequireCheckVersionRule extends AbstractEnforcerRule {

    @Inject
    private MavenProject project;

    @Inject
    private MavenSession session;

    @Inject
    private RuntimeInformation runtimeInformation;

    private String message;

    @Override
    public String getCacheId() {
        // 避免缓存冲突的唯一 ID
        return UUID.randomUUID().toString();
    }

    @Override
    public void execute() throws EnforcerRuleException {
        List<Dependency> dependencies = project.getDependencies();
//        getLog().info("dependencies: " + dependencies);
//        getLog().info("message: " + message);
        DependencyManagement dependencyManagement = project.getDependencyManagement();
//        getLog().info("dependencyManagement: " + dependencyManagement.getDependencies());

        // dependencies 的version 是否在 dependencyManagement 里，如果没有则报错
        // 遍历 dependencies 的依赖，并在 dependencyManagement 找到对应的配置，如果没有则报错
        for (Dependency dependency : dependencies) {
            dependency.getGroupId();
            Optional<Dependency> res = dependencyManagement.getDependencies().stream().filter(x ->
                    x.getGroupId().equals(dependency.getGroupId())
                            && x.getArtifactId().equals(dependency.getArtifactId())
                            && x.getVersion().equals(dependency.getVersion())
            ).findFirst();
            if (res.orElse(null) == null) {
                String msg = "模块名: " + project + " " + message;
                String detail = dependency + " 依赖项版本有误，请在 repository 模块进行管理依赖版本！";
                throw new EnforcerRuleException(msg + "\n" + detail);
            }
        }
    }
}
